<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="100" :formType="type" :isSubmitBtn="false" />
    <!--联系人信息 表格 -->
    <FilterTable
      ref="table"
      height="400px"
      :isPagination="false"
      :isSelectColumn="true"
      :columns="columns"
      :dataSource="dataList"
      :defaultSelections="defaultSelected"
      :selectionType="'single'"
      columnsRef="lxjczclglownerLinkerTable"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="onRowSelectChange"
      :onSyncTableData="handleSyncTableData"
    >
      <template slot="controls">
        <el-button size="small" type="primary" :style="{ display: isShow }" @click="saveRecordHandle">确定</el-button>
        <el-button size="small" type="primary" :style="{ display: isShow }" icon="el-icon-circle-plus-outline" @click="addRecordHandle">新增</el-button>
        <el-button size="small" type="primary" :style="{ display: isShow }" icon="el-icon-remove-outline" @click="removeRowHandle">删除</el-button>
      </template></FilterTable
    >
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import * as validate from '@/utils/validate.js';
import { getProvince, getCitys, getDistrict, getOwnerLinkerInfoAll, getPostCode } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
import { getUser } from '@/assets/js/auth';
import moment from 'moment';
import { isFormEmpty, confirmAction } from '../../../../../utils';
export default {
  name: 'addOwner_linkman',
  mixins: [dictionary],
  props: ['type', 'customerInfo'],
  data() {
    this.selectedRow = null;
    return {
      isShow: '',
      formList: this.createFormList(),
      defaultSelected: [],
      dataList: [],
      columns: this.createTableColumns(),
      tableSyncData: [] // 同步的table数据
    };
  },
  watch: {
    customerInfo(val) {
      this.checkChangeHandle();
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    // 同步table数据
    handleSyncTableData(list) {
      this.tableSyncData = list;
    },
    async checkChangeHandle() {
      console.log(this.type, this.customerInfo);
      // 新增且客户类型为私人时，将客户信息表数据带如联系人
      if (this.type === 'add' && this.customerInfo.ownerProperty === 80111001 && !this.customerInfo.ownerNo) {
        this.formList.forEach(x => {
          if (x.fieldName === 'contactorName' && !isFormEmpty(this.customerInfo.ownerName)) {
            x.initialValue = this.customerInfo.ownerName;
          }
          if (x.fieldName === 'contactorGender' && !isFormEmpty(this.customerInfo.gender)) {
            x.initialValue = this.customerInfo.gender;
          }
          if (x.fieldName === 'contactorMobile' && !isFormEmpty(this.customerInfo.mobile)) {
            x.initialValue = this.customerInfo.mobile;
          }
          if (x.fieldName === 'contactorPhone' && !isFormEmpty(this.customerInfo.phone)) {
            x.initialValue = this.customerInfo.phone;
          }
          if (x.fieldName === 'contactorOtherPhone' && !isFormEmpty(this.customerInfo.customerMobile)) {
            x.initialValue = this.customerInfo.customerMobile;
          }
          if (x.fieldName === 'concatTime' && !isFormEmpty(this.customerInfo.concatTime)) {
            x.initialValue = this.customerInfo.concatTime;
          }
          if (x.fieldName === 'contactorHobbyContact' && !isFormEmpty(this.customerInfo.contactorHobbyContact)) {
            x.initialValue = this.customerInfo.contactorHobbyContact;
          }
          if (x.fieldName === 'mainLink') {
            x.initialValue = 10041001;
          }
        });
        this.formList = [...this.formList];
        this.BaseTable.EXECUTE_INSERT({
          contactorName: this.customerInfo.ownerName,
          contactorGender: this.customerInfo.gender,
          // relationship: this.formList.find(x => x.fieldName === 'relationship').initialValue,
          mainLink: 10041001,
          contactorMobile: this.customerInfo.mobile,
          contactorPhone: this.customerInfo.phone,
          contactorOtherPhone: this.customerInfo.customerMobile,
          concatTime: this.customerInfo.concatTime,
          contactorHobbyContact: this.customerInfo.contactorHobbyContact
        });
        this.defaultSelected = this.BaseTable.GET_INSERT_ROWS();
      } else if (this.type !== 'add' || (this.type === 'add' && this.customerInfo.ownerNo)) {
        this.BaseTable.START_LOADING();
        let res = await getOwnerLinkerInfoAll({ ownerNo: this.customerInfo.ownerNo });
        if (res.resultCode === 200) {
          this.dataList = res.data || [];
        }
        this.BaseTable.STOP_LOADING();
      }
      if (this.type === 'show') {
        this.isShow = 'none';
      }
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '联系人姓名',
          fieldName: 'contactorName',
          placeholder: '请输入...',
          rules: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
          onInput: val => {
            this.handleRowinfoChange('contactorName', val);
          }
        },
        {
          type: 'SELECT',
          label: '联系人性别',
          fieldName: 'contactorGender',
          placeholder: '请选择...',
          itemList: this.createDictList('8012'),
          change: val => {
            this.handleRowinfoChange('contactorGender', val);
          }
          // rules: [{ required: true, message: '请选择性别', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '与客户关系',
          fieldName: 'relationship',
          placeholder: '请选择...',
          itemList: this.createDictList('8127'),
          change: val => {
            this.handleRowinfoChange('relationship', val);
          }
        },
        {
          type: 'INPUT',
          label: '联系人移动电话',
          fieldName: 'contactorMobile',
          placeholder: '请输入...',
          labelWidth: '115px',
          rules: [{ required: true, message: '联系人移动电话', trigger: 'blur' }],
          onInput: val => {
            this.handleRowinfoChange('contactorMobile', val);
          }
        },
        {
          type: 'INPUT',
          label: '联系人固定电话',
          fieldName: 'contactorPhone',
          placeholder: '请输入...',
          onInput: val => {
            this.handleRowinfoChange('contactorPhone', val);
          }
        },
        {
          type: 'INPUT',
          label: '联系人其他电话',
          fieldName: 'contactorOtherPhone',
          placeholder: '请输入...',
          onInput: val => {
            this.handleRowinfoChange('contactorOtherPhone', val);
          }
        },
        {
          type: 'CHECKBOX',
          label: '主联系人',
          fieldName: 'mainLink',
          initialValue: 10041002,
          options: { trueValue: 10041001, falseValue: 10041002 },
          style: { minWidth: '50px' },
          change: val => {
            this.selectedRow && (this.selectedRow.mainLink = val);
            if (this.selectedRow) {
              this.tableSyncData.forEach(item => {
                if (item._uid != this.selectedRow._uid) {
                  item.mainLink = 10041002;
                }
              });
            }
          }
        },
        {
          type: 'SELECT',
          label: '方便联系时间',
          fieldName: 'concatTime',
          placeholder: '请选择...',
          itemList: this.createDictList('8117'),
          change: val => {
            this.handleRowinfoChange('concatTime', val);
          }
        },
        {
          type: 'SELECT',
          label: '希望联络方式',
          fieldName: 'contactorHobbyContact',
          placeholder: '请选择...',
          itemList: this.createDictList('9123'),
          change: val => {
            this.handleRowinfoChange('contactorHobbyContact', val);
          }
          // rules: [{ required: true, message: '请选择喜欢联络方式', trigger: 'change' }]
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '联系人姓名',
          dataIndex: 'contactorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '联系人性别',
          dataIndex: 'contactorGender',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8012'),
          render: props => {
            return <div>{this.createDictText(props.row.contactorGender, '8012')}</div>;
          }
        },
        {
          title: '与客户关系',
          dataIndex: 'relationship',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8127'),
          render: props => {
            return <div>{this.createDictText(props.row.relationship, '8127')}</div>;
          }
        },
        {
          title: '主联系人',
          dataIndex: 'mainLink',
          sorter: true,
          filter: true,
          editable: true,
          defaultEditable: true,
          disabled: true,
          filterItems: this.createDictList('1004'),
          filterType: 'radio',
          editType: 'checkbox',
          editItems: [
            { text: '', trueValue: 10041001 },
            { text: '', falseValue: 10041002 }
          ]
        },
        {
          title: '联系人移动电话',
          dataIndex: 'contactorMobile',
          sorter: true,
          filter: true,
          filterType: 'input',
          rules: [{ required: true, message: '请输入联系人移动电话', trigger: 'blur' }]
        },
        {
          title: '联系人固定电话',
          dataIndex: 'contactorPhone',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '联系人其他电话',
          dataIndex: 'contactorOtherPhone',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '方便联系时间',
          dataIndex: 'concatTime',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8117'),
          render: props => {
            return <span>{this.createDictText(props.row.concatTime, '8117')}</span>;
          }
        },
        {
          title: '希望联络方式',
          dataIndex: 'contactorHobbyContact',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('9123'),
          render: props => {
            return <div>{this.createDictText(props.row.contactorHobbyContact, '9123')}</div>;
          }
        }
      ];
    },
    // 顶部信息输入变化
    handleRowinfoChange(fieldName, val) {
      if (this.selectedRow) {
        this.selectedRow[fieldName] = val;
      }
    },
    getData() {
      return this.tableSyncData;
    },
    async addRecordHandle() {
      this.BaseTable.EXECUTE_INSERT({
        mainLink: 10041002
      });
      this.$refs.formPanel.RESET_FORM();
      this.$nextTick(() => {
        this.defaultSelected = [this.tableSyncData[this.tableSyncData.length - 1]];
      });
    },
    async saveRecordHandle() {
      // 校验重复
      const name = this.formList.find(x => x.fieldName === 'contactorName').initialValue;
      const moblie = this.formList.find(x => x.fieldName === 'contactorMobile').initialValue;
      const phone = this.formList.find(x => x.fieldName === 'contactorPhone').initialValue;
      if (isFormEmpty(name)) {
        await confirmAction('联系人姓名不可为空');
        return;
      }
      if (isFormEmpty(moblie)) {
        await confirmAction('联系人移动电话不能为空');
        return;
      }
      for (let i = 0; i < this.tableSyncData.length; i++) {
        if (i !== this.selectedRow.$index && (this.tableSyncData[i].contactorName === name || this.tableSyncData[i].contactorMobile === moblie)) {
          await confirmAction('名字为' + name + '或手机号为' + moblie + '的联系人已存在，请勿添加重复联系人');
          return;
        }
      }
      let mainLink = false;
      this.formList.forEach(x => {
        this.tableSyncData[this.selectedRow.$index][x.fieldName] = x.initialValue;
        if (x.fieldName === 'mainLink' && x.initialValue === 10041001) {
          mainLink = true;
        }
      });
      console.log(mainLink, this.selectedRow.$index);
      // 处理主联系人
      if (mainLink) {
        for (let i = 0; i < this.tableSyncData.length; i++) {
          if (i !== this.selectedRow.$index) {
            this.tableSyncData[i].mainLink = 10041002;
          }
        }
      }
    },
    async removeRowHandle() {
      if (this.selectedRow.mainLink === 10041001) {
        await confirmAction('主联系人不可删除');
        return;
      }
      if (this.tableSyncData.length) {
        this.BaseTable.EXECUTE_DELETE();
        this.$nextTick(() => {
          this.defaultSelected = [this.tableSyncData[0]];
        });
        this.formList.forEach(x => {
          x.initialValue = this.tableSyncData[0][x.fieldName];
        });
      }
    },
    onRowSelectChange(row) {
      if (!row.length) {
        this.selectedRow = null;
      } else {
        this.selectedRow = row[0];
        console.log('selectedRow', this.selectedRow);
        this.formList.forEach(x => {
          let val = this.selectedRow[x.fieldName];
          x.initialValue = val;
        });
        this.formList = [...this.formList];
      }
    }
  },
  // 清空下拉框表当控件的值和下拉列表
  clearFormItem(item) {
    item.initialValue = undefined;
    item.itemList = [];
  }
};
</script>

<style lang="less" scoped>
.wrapper {
  height: calc(100vh - 135px);
}
</style>
